<template>
	<div>
		<div class="page-bar">
			<ul class="page-breadcrumb">
				<li>
					<a href="javascript:;" @click="backFn">用户管理</a>
					<i class="fa fa-circle"></i>
				</li>
				<li>
					<span>新建用户</span>
				</li>
			</ul>
		</div>
		<el-form :model="user" :rules="rules" ref="user" label-width="100px" class="demo-ruleForm">
			<el-form-item label="用户名" prop="username">
				<el-input v-model="user.username" maxlength="20"></el-input>
			</el-form-item>
			<el-form-item label="警号" prop="policeNo">
				<el-input v-model="user.policeNo" maxlength="6"></el-input>
			</el-form-item>

			<el-form-item label="身份证号" prop="idcard">
				<el-input v-model="user.idcard" maxlength="18"></el-input>
			</el-form-item>
			<el-form-item label="上传头像" prop="headPicture">
				<img type="headPicture" readonly='readonly' v-bind:src="numberValidateForm.headPicture" auto-complete="off" style='width:200px;max-height:200px;'></img>
				<el-upload class="upload-demo upload-btn" action='' :before-upload="uploadFile">
					<el-button type="primary">选择文件</el-button>
				</el-upload>
			</el-form-item>
			<el-form-item label="手机号" prop="mobile">
				<el-input v-model="user.mobile" maxlength="11"></el-input>
			</el-form-item>

			<el-form-item label="姓名" prop="name">
				<el-input v-model="user.name" maxlength="20"></el-input>
			</el-form-item>
			<!--<el-form-item label="上级部门" prop="sjbm">-->
				<!--<el-select v-model="ruleForm.sjbm" placeholder="请选择上级部门">-->
					<!--<el-option label="湖北省武汉市公安局" value="bubei"></el-option>-->
					<!--<el-option label="湖南省武汉市公安局" value="hunan"></el-option>-->
				<!--</el-select>-->
			<!--</el-form-item>-->
			<el-form-item label="角色" prop="roleId">
				<el-select v-model="user.roleId" placeholder="请选择角色">
					<el-option
							v-for="item in dataInfo.records"
							:key="item.id"
							:label="item.roleName"
							:value="item.id">
					</el-option>
				</el-select>
			</el-form-item>
			<el-form-item label="初始密码" prop="password">
				<el-input v-model="user.password" maxlength="12"></el-input>
			</el-form-item>
			<el-form-item label="备注" prop="remark">
				<el-input v-model="user.remark" maxlength="20"></el-input>
			</el-form-item>
			<el-form-item>
				<el-button type="primary" @click="submitForm('user')">确定</el-button>
				<el-button @click="backFn">取消</el-button>
			</el-form-item>
		</el-form>

	</div>
</template>

<script>

    import { UserSrv } from './user.service';
    import { RoleSrv } from "./../role/role.service";
    import { VersionSrv } from './../version/version.service';
    import { Notification } from 'element-ui';

	export default {
		data() {
            var validatePass2 = (rule, value, callback) => {
                UserSrv.checkUser({username:value}).then((result) =>{
                    if(result.code == 0 && result.data.exists){

                        callback(new Error('用户已经存在'));
                    }else{
                        callback();
					}
                })

            };
			return {
				dataInfo:{},
				numberValidateForm: {
					versionNo: '',
					headPicture: ''
				},
				user: {
					name: '',
					username: '',
					policeNo: '',
					idcard: '',
					mobile: '',
					password: '123456',
					sjbm: '',
					roleId: '',
					remark: ''
				},
				imageUrl: '',
				rules: {
					name: [{
							required: true,
							message: '请输入用户姓名',
							trigger: 'blur'
						},
						{ 
            				pattern: /(^[\u4E00-\u9FA5]+$)/, 
            				message: '只能输入汉字！', 
            				trigger: 'blur' 
            			}
					],
					username: [{
							required: true,
							message: '请输入用户名称',
							trigger: 'blur'
						},
						{
							min: 1,
							max: 8,
							message: '长度在 1 到 20 个字符',
							trigger: 'blur'
						},
                        { validator: validatePass2, trigger: 'blur' }
                        ,
                        {
                            pattern: /^(?:\d+|[a-zA-Z]+|[!@#$%^&*]+)$/,
                            message: '用户名不能包含特殊字符',
                            trigger: 'blur'
                        }
					],
					policeNo: [{
							required: true,
							message: '请输入警号',
							trigger: 'blur'
						},
						{
							min: 6,
							max: 6,
							message: '长度 6 个字符',
							trigger: 'blur'
						}
					],
					idcard: [{
							required: true,
							message: '请输入身份证号码',
							trigger: 'blur'
						},
						{
							min: 18,
							max: 18,
							message: '长度在 18 个字符',
							trigger: 'blur'
						},
            			{ 
            				pattern: /(^[1-9]\d{5}(18|19|([23]\d))\d{2}((0[1-9])|(10|11|12))(([0-2][1-9])|10|20|30|31)\d{3}[0-9Xx]$)|(^[1-9]\d{5}\d{2}((0[1-9])|(10|11|12))(([0-2][1-9])|10|20|30|31)\d{2}$)/, 
            				message: '身份证号码格式有误！', 
            				trigger: 'blur' 
            			}
					],
					mobile: [{
							required: true,
							message: '请输入手机号码',
							trigger: 'blur'
						},
						{
							min: 11,
							max: 11,
							message: '长度在 11 个字符',
							trigger: 'blur'
						},
						{ 
            				pattern: /(^1[3|5|6|7|8]{1}[0-9]{9}$)/, 
            				message: '手机号码格式有误！', 
            				trigger: 'blur' 
            			}
					],
					password: [{
							required: true,
							message: '请输入初始密码',
							trigger: 'blur'
						},
						{
							min: 6,
							max: 12,
							message: '长度在 6 到 12 个字符',
							trigger: 'blur'
						},
                        {
                            pattern: /^(?:\d+|[a-zA-Z]+|[!@#$%^&*]+)$/,
                            message: '密码不能包含特殊字符',
                            trigger: 'blur'
                        }
					],
					sjbm: [{
						required: true,
						message: '请选择上级部门',
						trigger: 'change'
					}],
					roleId: [{
						required: true,
						message: '请选择角色',
						trigger: 'change'
					}]
				}
			};
		},
		methods: {
			uploadFile(file) {
				let fd = new FormData();
				fd.append('file', file);
				VersionSrv.uploadFile(fd).then(req => {
					if(req.code === 0) {
						this.numberValidateForm.headPicture = globalConfig.apiPath.v1+req.data.url;
					}
				})
				return false;
			},
			getRoleList() { //获取角色列表
				let params = {
					pageNo: 1,
					pageSize: 10	
				}

				RoleSrv.list(params).then(req => {
					if(req.code === 0) {
						this.dataInfo = req.data;

					}

				})
			},
			submitForm(formName) {
				this.$refs[formName].validate((valid) => {
					if(valid) {

                        let params = this.user;
                        params.headPicture = this.numberValidateForm.headPicture;
                        UserSrv.createUser(params).then((result) =>{
                            if(result.code === 0){
                            	Notification.success({
									title: '新建用户',
						          	message: '操作成功',
						          	offset: 50
						        })
                                this.backFn();
                            }
                        })
					} else {
						console.log('error submit!!');
						return false;
					}
				});
			},
			backFn: function() {
				this.$router.push('/');
			},
			/*handleAvatarSuccess(res, file) {
				this.imageUrl = URL.createObjectURL(file.raw);
			},*/
			beforeAvatarUpload(file) {
				const isJPG = file.type === 'image/jpeg';
				const isLt2M = file.size / 1024 / 1024 < 2;

				if(!isJPG) {
					this.$message.error('上传头像图片只能是 JPG 格式!');
					return;
				}
				if(!isLt2M) {
					this.$message.error('上传头像图片大小不能超过 2MB!');
					return;
				}
				return false;
			}
		},
		created(){
	      	this.getRoleList();
	    }
	}
</script>

<style scoped>
	.el-form {
		width: 500px;
		margin: 0 auto;
		margin-top: 20px;
	}
	
	.el-select {
		width: 100%;
	}
</style>